package com.example.myapplication;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.snackbar.Snackbar;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class AddBookActivity extends AppCompatActivity {

    private static final String TAG =
            MainActivity.class.getSimpleName();

    private HttpURLConnection connection;
    private InputStream inputStream;
    private BufferedReader bufferedReader;
    private String ISBNNumber="";

    public static List<String> bookData = new ArrayList<>();

    //将数据储存到主线程
    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            String data = msg.getData().getString("data");
            TextView InformationText=(TextView) findViewById(R.id.textView2);
            Button AddBookIntoList = findViewById(R.id.AddBookIntoList);

            SharedPreferences sharedPreferences = getSharedPreferences("Configure",MODE_PRIVATE);

            boolean printThePrice = sharedPreferences.getBoolean("PrintPrice",false);
            int SizeOfWord =sharedPreferences.getInt("Size",2);

            //设置字号
            InformationText.setTextSize(TypedValue.COMPLEX_UNIT_SP,SizeOfWord*10);

            //解析数据
            try {
                JSONObject jsonObject=new JSONObject(data);

                if(jsonObject.optInt("ret")==1){
                    InformationText.setText("查找失败："+jsonObject.optString("msg"));

                    AddBookIntoList.setVisibility(View.GONE);

                }else if((jsonObject.optInt("ret")==0)&&(!jsonObject.optString("data").equals(null))){
                    JSONObject jsData = new JSONObject(jsonObject.optString("data"));
                    Log.d(TAG,jsData.optString("name"));
                    Log.d(TAG,jsData.optString("author"));
                    Log.d(TAG,jsData.optString("publishing"));
                    Log.d(TAG,jsData.optString("published"));

                    if(!printThePrice){
                        InformationText.setText("书名："+jsData.optString("name")+"\n作者："+jsData.optString("author")+"\n出版社："+jsData.optString("publishing")+"\n出版日期："+jsData.optString("published"));
                    }
                    else{
                        InformationText.setText("书名："+jsData.optString("name")+"\n作者："+jsData.optString("author")+"\n出版社："+jsData.optString("publishing")+"\n出版日期："+jsData.optString("published")+"\n价格："+jsData.optString("price"));
                    }

                    AddBookIntoList.setVisibility(View.VISIBLE);
                }else if((jsonObject.optInt("ret")==0)&&(jsonObject.optString("data").equals(null))){
                    InformationText.setText("未找到相关书籍");

                    AddBookIntoList.setVisibility(View.GONE);
                }

            }catch (Exception e){
                e.printStackTrace();
            }

            AddBookIntoList.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //重复
                    for(int i=0;i<bookData.size();i++){
                        try {
                            JSONObject jsonObject =new JSONObject(bookData.get(i));
                            if (jsonObject.optString("id").equals(ISBNNumber)){
                                Snackbar.make(findViewById(R.id.addbookactivity), "这本书已经在书架上了",
                                                Snackbar.LENGTH_SHORT)
                                        .show();
                                return ;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    try {
                        JSONObject jsonObject = new JSONObject(data);
                        bookData.add(jsonObject.optString("data"));
                        Log.d(TAG,jsonObject.optString("data"));

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });

            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addbook);

        Button SearchBook = findViewById(R.id.SearchButton);
        //按下查询按钮请求数据
        SearchBook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText SearchNumber = findViewById(R.id.SearchNumber);
                ISBNNumber = SearchNumber.getText().toString();
                Log.d(TAG,ISBNNumber);

                if(ISBNNumber.equals("")){
                    Log.d(TAG,"查找为空");
                    TextView InformationText=(TextView) findViewById(R.id.textView2);
                    InformationText.setText("查找不可为空");
                    return;
                }

                //创建线程获取数据
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String data = getData(ISBNNumber,"12753.935c1581d9e43805ae764ede49e42802.6685898c5a99f3710ffa6657f2701dad");

                        //
                        Message message = Message.obtain();
                        Bundle bundle = new Bundle();
                        bundle.putString("data",data);
                        message.setData(bundle);

                        //
                        mHandler.sendMessage(message);
                    }
                }).start();
            }
        });

    }

    private String getData(String number,String apiKey){

        try {

            URL url=new URL("https://api.jike.xyz/situ/book/isbn/"+number+"?apikey="+apiKey);
            connection = (HttpURLConnection) url.openConnection();

            if(connection.getResponseCode()==200){
                inputStream = connection.getInputStream();
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

                StringBuilder stringBuilder=new StringBuilder();
                for(String line = "";(line = bufferedReader.readLine())!=null;){
                    stringBuilder.append(line);
                }
                return stringBuilder.toString();
            }

        }catch(Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (bufferedReader!=null) bufferedReader.close();
                if(inputStream!=null) inputStream.close();
                if(connection!=null) connection.disconnect();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }

    /*@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.menu_options,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int itemID = item.getItemId();

        switch (itemID){
            case R.id.Configure:
                Log.d(TAG,"111111");
                return true;
            default:

                break;
        }
        return true;
    }
*/
}